<template>
  <div>
    <div v-show="toggle2">
      <div style="width:100%;background-color:#f2f2f2;height:42px;">
        <span style="margin-left:20px;line-height:42px;float: left">转化漏斗分析</span>
      </div>
    </div>
    <el-row :gutter="20">
      <el-col :span="4">
        <el-card class="list-card">
          <h1 style="margin-top: 1px;">使用该模型已保存的图标</h1>
          <el-row>
            <li v-for="(item,index) in dataList" :key="index" class="list-title-li">
              <span class="list-title" @click="setCondition(item)">{{item.model_name}}<i
                  class="el-icon-close list-delete" @click="handleDelete(item)"></i></span>
            </li>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="20">
        <div class="card1">
          <div class="index">
            <div>
              <span style="font-weight:600;">建立漏斗</span>
              <el-button type="text" style="float: right;" @click="openVisible"><img src="@/assets/icon-save.png"
                  class="save-icon" /><span style="float: right;margin-top: 7px;margin-left: 4px;">保存</span></el-button>
              <div class="detail" v-for="(options,index) in options1List" :key="'key1'+index">
                <span>
                  <el-select v-model="value1List[index]" placeholder="请选择">
                    <el-option v-for="item in options" :key="item.event_code" :label="item.event_name"
                      :value="item.event_code"></el-option>
                  </el-select>
                </span>
                <span>
                  <i class="el-icon-plus" style="margin-left:4px;" @click="addOption1"></i>
                  <i class="el-icon-minus" style="margin-left:4px;" @click="removeOption1"></i>
                </span>
              </div>
              <el-divider></el-divider>
              <span style="font-weight:600;">过滤条件</span>
              <div class="detail2" v-for="(options,index) in options2List" :key="'key2'+index">
                <span>
                  <el-select v-model="value2List[index]" placeholder="请选择" @change="getDropDownListValue(index)">
                    <el-option v-for="item in options" :key="item.name" :label="item.name" :value="item.name">
                    </el-option>
                  </el-select>
                </span>
                <span>等于</span>
                <span>
                  <el-select v-model="value3List[index]" placeholder="请选择">
                    <el-option v-for="item in options3List[index]" :key="item.value" :label="item.name"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </span>
                <span>
                  <i class="el-icon-plus" style="margin-left:4px;" @click="addOption2"></i>
                  <i class="el-icon-minus" style="margin-left:4px;" @click="removeOption2"></i>
                </span>
              </div>

              <div style="text-align:right;">
                <el-button style="width:68px;background-color:#3A4267;color:#fff;border-radius:40px;"
                  @click="hopperAnalysis">
                  查询</el-button>
              </div>
            </div>
          </div>
          <div style="margin:20px 0 0 0;padding:30px 40px 0 40px;background-color:#fff;height:100%;">
            <div class="block" style="float:left;">
              <el-date-picker v-model="dateValue" value-format="yyyy-MM-dd" type="daterange" align="right" unlink-panels
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
              </el-date-picker>
            </div>
            <div style="float:left;margin-left:60px;">
              <el-radio-group v-model="radio1" size="middle" @change="changeTheme">
                <el-radio-button label="转化"></el-radio-button>
                <el-radio-button label="转化趋势"></el-radio-button>
              </el-radio-group>
              <span>
                <el-select v-model="optionsValue" placeholder="总体 的 转化率" size="middle" @change="initLineOption">
                  <el-option v-for="item in options" :key="item.value" :label="item.name" :value="item.value">
                  </el-option>
                </el-select>
              </span>
            </div>
            <div style="float:right;">
              <el-radio-group v-model="radio2" @change="toggleMethod1">
                <el-radio-button :label="1">
                  <img :src="img4" style="width:12px;height:12px;" />
                </el-radio-button>
                <el-radio-button :label="2">
                  <img :src="img5" style="width:12px;height:12px;" />
                </el-radio-button>
              </el-radio-group>
            </div>
            <div v-show="toggle1" id="main" style="width: 1000px;height:400px;margin-top:10%;" v-loading="loading" />

            <el-table v-show="!toggle1" :data="tableData1" style="width: 100%;margin-bottom: 20px;" row-key="id" border
              default-expand-all :tree-props="{children: 'children', hasChildren: 'hasChildren'}" v-loading="loading">
              <!-- <el-table-column prop="name" label width="240"></el-table-column> -->
              <el-table-column v-for="(column,index) in tableData1Head" :key="index" :prop="column.prop"
                :label="column.label" width="180">
                <template slot-scope="{row}">
                  <div v-if="Array.isArray(row[column.prop])">
                    <p v-for="(status, index) in row[column.prop]" :key="index">{{status}}</p>
                  </div>
                  <span v-else>{{row[column.prop]}}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div v-show="!toggle2">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="用户列表" name="first">
              <div style="text-align:right;">
                <el-button style="width:68px;background-color:#ff8b2f;color:#fff;border-radius:40px;"
                  @click="toggleMethod2">返回</el-button>
              </div>
              <p style="text-align:left;font-size:8px;">
                <i class="el-icon-warning"></i>
                <span>用户列表抽样展示部分用户用于进一步细查单用户行为，仅展示具有用户属性的用户（需通过SDK上报），最多1000条</span>
              </p>
              <el-table :data="tableData2" style="width: 100%" max-height="800"
                :default-sort="{prop: 'date', order: 'descending'}">
                <el-table-column v-for="(column,index) in tableData2Head" :key="index" :prop="column.prop"
                  :label="column.label" sortable width="120"></el-table-column>
              </el-table>
              <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
                layout="total, prev, pager, next" :total="total">
              </el-pagination>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-col>
    </el-row>
    <el-dialog title="保存图表" :visible.sync="saveVisible" width="30%">
      <span style="float:left;font-size:13px">图表名称</span>
      <el-input v-model="modelName" placeholder="请输入图表名称"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="saveVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave" :disabled="disabled">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import echarts from "echarts";

  export default {
    name: "ReportContent",
    props: {},
    data() {
      return {
        saveVisible: false,
        disabled: false,
        modelName: '',
        paramsName: '',
        loading:false,
        currentPage: 1,
        pageSize: 10,
        total: 0,
        toggle1: true,
        toggle2: true,
        radio1: "转化",
        radio2: 1,
        img4: require("@/assets/broken.png"),
        img5: require("@/assets/can.png"),
        activeName: "first",
        options: [],
        optionsValue: "",
        options1: [],
        options1List: [],
        value1List: [],
        options2: [],
        options2List: [],
        value2List: [],
        //options3: [],
        options3List: [],
        value3List: [],
        pickerOptions: {
          shortcuts: [{
              text: "最近一周",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit("pick", [start, end]);
              },
            },
            {
              text: "最近一个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit("pick", [start, end]);
              },
            },
            {
              text: "最近三个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit("pick", [start, end]);
              },
            },
          ],
        },
        dateValue: "",
        tableData2Head: [],
        tableData2: [],
        tableData1Head: [],
        tableData1: [],
        dataList: [],
        option: {
          //color: ["#48abfe", "#00d06e", "#3be294", "#ffdcba"],
          tooltip: {
            //trigger: "axis",
          },
          legend: {
            icon: "rect",
            itemWidth: 20,
            itemHeight: 6,
            bottom: "0%",
            data: [],
          },
          grid: {
            top: "10%",
            left: "3%",
            right: "4%",
            bottom: "25%",
            containLabel: true,
          },
          yAxis: [{
            type: "value",
            axisLabel: {
              show: true,
              interval: "auto",
              formatter: "{value} %",
            },
            splitLine: {
              lineStyle: {
                type: "dashed",
                color: "#DDD",
              },
            },
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            show: true,
          }, ],
          xAxis: [{
            type: "category",
            axisLabel: {
              interval: "auto",
              //show: true,
              splitNumber: 15,
              textStyle: {
                fontSize: 12,
                color: "#656565",
              },
            },
            axisLine: {
              show: true,
            },
            axisTick: {
              show: false,
            },
            data: [],
          }, ],
          series: [],
        },
        respdata: "",
      };
    },
    computed: {},
    created() {
      this.getList()
    },
    mounted() {
      this.getEventList();
      this.getDropDownListKey();
      this.initChart();
    },
    watch: {},
    methods: {
      handleCurrentChange(val) {
        //console.log(val)
        this.currentPage = val;
        this.hopperAnalysisDetail();
      },
      toggleMethod1() {
        this.toggle1 = !this.toggle1;
      },
      toggleMethod2(val) {
        //console.log(val);
        this.toggle2 = !this.toggle2;
        if (val) {
          this.paramsName = val;
          this.currentPage = 1;
          this.hopperAnalysisDetail();
        }
      },
      handleClick(tab, event) {
        console.log(tab, event);
      },
      hopperAnalysisDetail() {
        this.loading = true
        var steps = [];
        for (var i = 0; i < this.value1List.length; i++) {
          if (this.value1List[i]) {
            steps.push({
              "eventcode": this.value1List[i]
            });
          }
        }
        var filterParameter = [];
        for (var i = 0; i < this.value3List.length; i++) {
          if (this.value3List[i]) {
            filterParameter.push(this.value3List[i]);
          }
        }
        var params = {
          steps: JSON.stringify(steps),
          filterParameter: "[" + filterParameter + "]",
          startDate: this.dateValue[0],
          endDate: this.dateValue[1],
          stepNow: this.paramsName,
          pageNo: this.currentPage,
          pageSize: this.pageSize
        };

        if (this.paramsName && this.dateValue && steps.length > 0 && filterParameter.length > 0) {
          this.$http.post(
            "http://127.0.0.1:8080/userprofile-platform/v1/DataAnalysis/hopperAnalysisDetail",
            params
          ).then((res) => {
            if (res) {
              console.log(res.data);
              if (res.data.flag == true) {
                this.initTable2(res.data.data);
                this.loading = false
              }
            }
          });
        }
      },
      hopperAnalysis() {
        this.loading = true
        if (this.options1List.length >= 2) {
          var steps = [];
          for (var i = 0; i < this.value1List.length; i++) {
            if (this.value1List[i]) {
              steps.push({
                "eventcode": this.value1List[i]
              });
            }
          }
          var filterParameter = [];
          for (var i = 0; i < this.value3List.length; i++) {
            if (this.value3List[i]) {
              filterParameter.push(this.value3List[i]);
            }
          }
          var params = {
            steps: JSON.stringify(steps),
            filterParameter: "[" + filterParameter + "]",
            startDate: this.dateValue[0],
            endDate: this.dateValue[1],
          };

          if (this.dateValue && steps.length > 0 && filterParameter.length > 0) {
            this.$http.post(
              "http://127.0.0.1:8080/userprofile-platform/v1/DataAnalysis/hopperAnalysis",
              params
            ).then((res) => {
              if (res) {
                //console.log(res.data);
                if (res.data.flag == true) {
                  this.respdata = res.data.data;
                  this.initTable1();
                  //this.initOption();
                  this.changeTheme(this.radio1);
                  this.loading = false
                }
              }
            });
          }
        } else {
          this.$message.error('构建漏斗图至少需要两项条件')
          this.loading = false
        }
      },
      initBarOption() {
        this.option.xAxis[0].data = this.respdata.eventNames;
        var respDetails = this.respdata.eventDetails[0]
        var overview = respDetails[respDetails.length - 1].overview;
        var barData = [];
        for (var i = 0; i < overview.length; i++) {
          barData.push(overview[i].users);
        }
        var barSeries = [];
        barSeries.push({
          data: barData,
          type: "bar",
          barWidth: '25%',
          itemStyle: {
            emphasis: {
              barBorderRadius: 15
            },
            normal: {
              barBorderRadius: 15,
              color: new this.$echarts.graphic.LinearGradient(
                0, 0, 0, 1,
                [{
                    offset: 0,
                    color: '#91B6FD'
                  },
                  {
                    offset: 0.5,
                    color: '#719FFD'
                  },
                  {
                    offset: 1,
                    color: '#4A86FF'
                  }
                ]
              )
            },
          },
        });
        this.option.series = barSeries;
        this.option.yAxis[0].axisLabel = {
            formatter: '{value}'
          },
          this.chart.setOption(this.option, true);
      },
      initOptions() {
        var respDetails = this.respdata.eventDetails[0]
        var overview = respDetails[respDetails.length - 1].overview;
        var option = [];
        for (var i = 1; i < overview.length; i++) {
          option.push({
            value: overview[i].step,
            name: '第' + (overview[i].step - 1) + '步到第' + overview[i].step + '步'
          });
        }
        this.options = option;

      },
      initLineOption() {
        console.log(this.optionsValue)
        var xData = [];
        var lineData = [];
        var respDetails = this.respdata.eventDetails[0];
        for (var i = 0; i < respDetails.length - 1; i++) {
          xData.push(respDetails[i].datadate);
          lineData.push(respDetails[i].overview[this.optionsValue - 1].rate);
        }
        var lineSeries = [];
        lineSeries.push({
          data: lineData,
          type: "line",
          itemStyle: {
              normal: {
                color: '#4A86FF',
                lineStyle: {
                  color: '#4A86FF'
                }
              }
            },
        });
        this.option.xAxis[0].data = xData;
        this.option.series = lineSeries;
        this.option.yAxis[0].axisLabel = {
            formatter: '{value}%'
          },
          this.chart.setOption(this.option, true);
      },
      initTable1() {
        var tableHead = [];
        var tableData = [];
        var respName = this.respdata.eventNames;
        var respDetails = this.respdata.eventDetails[0];
        //内容
        for (var i = 0; i < respName.length; i++) {
          tableData.push({
            name: respName[i]
          })
        }
        //表头
        tableHead.push({
          label: "",
          prop: "name"
        });
        for (var i = 0; i < respDetails.length - 1; i++) {
          //表头
          tableHead.push({
            label: respDetails[i].datadate,
            prop: "date" + i
          })
          var overview = respDetails[i].overview;
          //内容
          for (var j = 0; j < overview.length; j++) {
            var arr = [];
            arr.push(overview[j].users);
            arr.push(overview[j].rate + '%');
            tableData[j]["date" + i] = arr;
          }
        }
        this.tableData1Head = tableHead;
        this.tableData1 = tableData;

      },
      initTable2(respdata) {
        this.total = respdata.total;
        this.pageSize = respdata.pageSize;
        this.currentPage = respdata.currentPage;
        respdata = respdata.list;
        var tableHead = [];
        var tableData = [];
        //内容
        for (var i = 0; i < respdata.length; i++) {
          tableData.push({
            userId: respdata[i].userId
          })
          var tagArray = respdata[i].tagArray;
          for (var j = 0; j < tagArray.length; j++) {
            tableData[i]["col" + j] = tagArray[j].tagId;
          }
        }
        //表头
        tableHead.push({
          label: "用户ID",
          prop: "userId"
        })
        for (var i = 0; i < respdata[0].tagArray.length; i++) {
          //表头
          tableHead.push({
            label: respdata[0].tagArray[i].tagName,
            prop: "col" + i
          })

        }
        this.tableData2Head = tableHead;
        this.tableData2 = tableData;

      },
      getEventList() {
        this.$http
          .post(
            "http://127.0.0.1:8080/userprofile-platform/v1/DataAnalysis/eventList", {}
          )
          .then((res) => {
            if (res) {
              var respdata = res.data.data;
              this.options1 = respdata;
              this.addOption1();
            }
          });
      },
      getDropDownListKey() {
        this.$http
          .post(
            "http://127.0.0.1:8080/userprofile-platform/v1/DataAnalysis/dropDownListKey", {}
          )
          .then((res) => {
            if (res) {
              var respdata = res.data.data;
              this.options2 = respdata.list;
              this.addOption2();
            }
          });
      },
      getDropDownListValue(index) {
        if (this.value2List[index] != "") {
          this.$http
            .post(
              "http://127.0.0.1:8080/userprofile-platform/v1/DataAnalysis/dropDownListValue?level_2_name=" +
              this.value2List[index], {
                level_2_name: this.value2List[index]
              }
            )
            .then((res) => {
              if (res) {
                var respdata = res.data.data.list;
                var option = [];
                for (var i = 0; i < respdata.length; i++) {
                  option.push({
                    value: JSON.stringify(respdata[i]),
                    name: respdata[i].name,
                  });
                }
                //this.options3List[index] = option;
                this.$set(this.options3List, index, option);
                this.value3List[index] = "";
              }
            });
        } else {
          this.options3List[index] = "";
          this.value3List[index] = "";
        }

      },
      addOption1() {
        this.options1List.push(this.options1);
        this.value1List.push("");
      },
      removeOption1() {
        if (this.options1List.length > 1) {
          this.options1List.pop();
          this.value1List.pop();
        }
      },
      addOption2() {
        this.options2List.push(this.options2);
        this.value2List.push("");
        this.options3List.push("");
        this.value3List.push("");
      },
      removeOption2() {
        if (this.options2List.length > 1) {
          this.options2List.pop();
          this.value2List.pop();
          this.options3List.pop();
          this.value3List.pop();
        }
      },
      //切换主题
      changeTheme(val) {
        //console.log(val);
        if (val == '转化') {
          //柱形图
          this.initBarOption();
        } else if (val == '转化趋势') {
          //折线图
          this.initOptions();
          if (this.options.length > 0) {
            this.optionsValue = this.options[0].value;
          }
          this.initLineOption();
        }

      },
      initChart() {
        // 通过 echarts.init 方法初始化一个 echarts 实例并通过 setOption 方法生成一个简单的柱状图
        this.chart = echarts.init(document.getElementById("main"));
        // this.chart = echarts.init(this.$el)

        // 使用刚指定的配置项和数据显示图表。
        this.chart.setOption(this.option);
        var thisvue = this;
        this.chart.on('click', function (params) {
          //console.log(params)
          if (params.seriesType == "bar") {
            thisvue.toggleMethod2(params.name); //
          }
        });
      },
      //列表
      getList() {
        this.$http.post("http://127.0.0.1:8080/userprofile-platform/v1/modelList/listHopperModel", {}).then(res => {
          if (res.data.flag && res.data.code == 1) {
            this.dataList = res.data.data.list
          } else {
            this.$message.error(res.data.msg)
          }
        })
      },
      //打开判断
      openVisible() {
        console.log(this.options3List)
        if (this.options1List.length < 2) {
          this.$message.error('构建漏斗图至少需要两项条件')
        } else if (this.dateValue.length == 0) {
          this.$message.error('请选择日期')
        } else {
          this.saveVisible = true
        }
      },
      //保存
      handleSave() {
        this.disabled = true
        var steps = [];
        for (var i = 0; i < this.value1List.length; i++) {
          if (this.value1List[i]) {
            steps.push({
              "eventcode": this.value1List[i]
            });
          }
        }
        var filterParameter = [];
        for (var i = 0; i < this.value3List.length; i++) {
          if (this.value3List[i]) {
            filterParameter.push(this.value3List[i]);
          }
        }
        var params = {
          steps: JSON.stringify(steps),
          filterParameter: "[" + filterParameter + "]",
          startDate: this.dateValue[0],
          endDate: this.dateValue[1],
          modelName: this.modelName
        };
        this.$http.post("http://127.0.0.1:8080/userprofile-platform/v1/modelList/hopperAnalysisModel", params).then(
          res => {
            if (res.data.code == 100) {
              this.$message.success(res.data.msg)
              this.saveVisible = false
              this.disabled = false
              this.getList()
            } else {
              this.$message.error(res.data.msg)
              this.disabled = false
            }
          })
      },
      //删除
      handleDelete(item) {
        this.$confirm('确认删除此条数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const URL = "http://127.0.0.1:8080/userprofile-platform/v1/modelList/deleteHopperModel?modelId=" + item
            .model_id
          this.$http.post(URL, {}).then(res => {
            if (res.data.code == 100) {
              this.$message.success(res.data.msg)
              this.getList()
            } else {
              this.$message.error(res.data.msg)
            }
          })
        }).catch(() => {

        })
      },

      //生成查询条件
      async setCondition(data) {
        this.options1List = []
        this.options2List = []
        this.options3List = []
        this.dateValue = [data.start_date, data.end_date]
        const steps = JSON.parse(data.steps)
        const filterParameter = JSON.parse(data.filter_parameter)
        for (let i = 0; i < steps.length; i++) {
          this.options1List.push(this.options1)
          this.value1List[i] = steps[i].eventcode
        }
        for (let i = 0; i < filterParameter.length; i++) {
          this.options2List.push(this.options2)
          await this.options2.forEach(item => {
            if (item.field == filterParameter[i].field) {
              this.value2List[i] = item.name
              this.$http.post(
                "http://127.0.0.1:8080/userprofile-platform/v1/DataAnalysis/dropDownListValue?level_2_name=" +
                item.name).then(res => {
                if (res.data.code == 1) {
                  let obj = []
                  for (let k = 0; k < res.data.data.list.length; k++) {
                    obj.push({
                      value: JSON.stringify(res.data.data.list[k]),
                      name: res.data.data.list[k].name,
                    })
                  }
                  this.options3List.push(obj)
                  this.value3List[i] = JSON.stringify(filterParameter[i])
                }
              })
            }
          })
        }
      },
      getRowClass({
        rowIndex
      }) {
        if (rowIndex == 0) {
          return "background:RGB(254,242,234)";
        } else {
          return "";
        }
      },
    },
    destroyed() {},
  };

</script>

<style scoped>
  .card1 {
    text-align: left;
    font-size: 18px;
  }

  .index {
    min-height: 200px;
    padding: 20px;
    background-color: #fff;
    color: #303133;
    text-align: left;
  }

  .detail {
    padding: 30px 0;
  }

  .detail2 {
    padding: 10px 0 0 0;
  }

  .el-divider--horizontal {
    margin: 0;
    margin-bottom: 20px;
  }

  .card {
    padding: 30px 20px 20px 20px;
    background-color: #fff;
    color: #303133;
    text-align: left;
    font-size: 18px;
    border-right: 1px solid #f7f8fa;
  }

  .imgr {
    width: 16px;
    height: 16px;
    margin-right: 8px;
    float: right;
    margin-top: 3px;
  }


  .list-card {
    height: 850px;
  }

  .list-title-li {
    list-style: none;
    text-align: left;
    margin-top: 10px;
  }

  .list-title {
    margin-left: 10px;
    color: #999;
    cursor: pointer;
  }

  .list-delete {
    float: right;
    margin-top: 3px;
    font-size: 17px;
    color: black;
    font-weight: 800;
    cursor: pointer;
  }

  .save-icon {
    width: 27px;
    height: 27px;
  }

  .el-dialog__wrapper /deep/ .el-dialog__title {
    line-height: 24px;
    font-size: 18px;
    color: #303133;
    float: left;
  }

  .el-dialog__wrapper /deep/ .el-dialog {
    position: relative;
    margin: 0 auto 50px;
    border-radius: 15px;
    -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    width: 50%;
  }

</style>
